using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace url2jpeg
{
    public partial class script : LocalizedUserControl
    {
        scriptData  m_currentScript;
        int         m_timeout;
        DateTime    m_completeTime;
        bool        m_bExit, m_bRunning;

        public script()
        {
            InitializeComponent();
            navigator1.NavigationCompleteEvent += new url2jpegCtn.navigator.NavigationCompleteHandler(navigator1_NavigationCompleteEvent);
        }

        private void DataToForm(scriptData data)
        {
            txtName.Text = data.name;
            txtURL.Text = data.url;
            txtInitialSizeX.Text = data.initialSize.Width.ToString();
            txtInitialSizeY.Text = data.initialSize.Height.ToString();
            btnAutoResize.Checked = data.bAutoResize;
            btnRemoveScrollBars.Checked = data.bRemoveScrollBar;
            txtTimeout.Text = data.timeOut.ToString();
            txtWait.Text = data.waitBeforeCapture.ToString();
            switch (data.capture)
            {
                case captureMode.Full:
                    btnFullPage.Checked = true;
                    break;
                case captureMode.Manual:
                    btnManual.Checked = true;
                    break;
                case captureMode.Document:
                    btnCaptureContent.Checked = true;
                    break;
            }
            txtCapture.Text = data.captureParam.ToString();
            txtCapture.Tag = data.captureParam;
            if (txtCapture.Text.Length == 0)
            {
                btnManual.Enabled = false;
                btnCaptureContent.Enabled = false;
            }
            else
            {
                btnManual.Enabled = true;
                btnCaptureContent.Enabled = true;
            }

            switch (data.resize)
            {
                case resizeMode.No:
                    btnNoResize.Checked = true;
                    break;
                case resizeMode.Fixed:
                    btnFixedSize.Checked = true;
                    break;
                case resizeMode.Percent:
                    btnPercentOriginal.Checked = true;
                    break;
            }
            try
            {
                txtWidth.Text = data.resizeParam.Width.ToString();
                txtHeight.Text = data.resizeParam.Height.ToString();
                txtInflateX.Text = data.sizeOffset.Width.ToString();
                txtInflateY.Text = data.sizeOffset.Height.ToString();
            }
            catch
            { }
            switch (data.format)
            {
                case formatMode.Jpeg:
                    btnJPEG.Checked = true;
                    break;
                case formatMode.Png:
                    btnPNG.Checked = true;
                    break;
                case formatMode.Bmp:
                    btnBMP.Checked = true;
                    break;
            }
        }

        private bool FormToData(scriptData data)
        {
            bool bResult = false;
            try
            {

                data.name = txtName.Text;
                data.url = txtURL.Text;
                data.initialSize = new Size(navigation.GetTextInt(txtInitialSizeX), navigation.GetTextInt(txtInitialSizeY));
                data.bAutoResize = btnAutoResize.Checked;
                data.bRemoveScrollBar = btnRemoveScrollBars.Checked;
                data.sizeOffset.Width = navigation.GetTextInt(txtInflateX);
                data.sizeOffset.Height = navigation.GetTextInt(txtInflateY);
                data.timeOut = Convert.ToInt32(txtTimeout.Text);
                data.waitBeforeCapture = Convert.ToInt32(txtWait.Text);
                if (btnFullPage.Checked) data.capture = captureMode.Full;
                else if (btnManual.Checked) data.capture = captureMode.Manual;
                else if (btnCaptureContent.Checked) data.capture = captureMode.Document;
                data.captureParam = (Rectangle)txtCapture.Tag;
                if (btnNoResize.Checked) data.resize = resizeMode.No;
                else if (btnFixedSize.Checked) data.resize = resizeMode.Fixed;
                else if (btnPercentOriginal.Checked) data.resize = resizeMode.Percent;
                data.resizeParam.Width = navigation.GetTextInt(txtWidth);
                data.resizeParam.Height = navigation.GetTextInt(txtHeight);
                if (btnJPEG.Checked) data.format = formatMode.Jpeg;
                else if (btnPNG.Checked) data.format = formatMode.Png;
                else if (btnBMP.Checked) data.format = formatMode.Bmp;
                bResult = true;
            }
            catch
            {
            }
            return bResult;
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            scriptData data = new scriptData();
            data.name = "Change name";
            data.url = "http://";
            data.initialSize = new Size(1024, 768);
            data.capture = captureMode.Full;
            data.resize = resizeMode.No;
            data.format = formatMode.Jpeg;
            NewScript(data);
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (!groupBox1.Enabled)
            {
                scriptData data = lstScript.SelectedItem as scriptData;
                if (data != null)
                {
                    DataToForm(data);
                    groupBox1.Enabled = true;
                    m_currentScript = data;
                    txtName.Focus();
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (lstScript.SelectedItem != null)
            {
                lstScript.Items.Remove(lstScript.SelectedItem);
                groupBox1.Enabled = false;
            }
        }

        public void NewScript(scriptData data)
        {
            if (!groupBox1.Enabled)
            {
                DataToForm(data);
                groupBox1.Enabled = true;
                m_currentScript = null;
                txtName.Focus();
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (m_currentScript != null)
            {
                if (FormToData(m_currentScript))
                {
                    lstScript.Refresh();
                    groupBox1.Enabled = false;
                    m_currentScript = null;
                }
            }
            else
            {
                scriptData data = new scriptData();
                if (FormToData(data))
                {
                    lstScript.Items.Add(data);
                    groupBox1.Enabled = false;
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            groupBox1.Enabled = false;
        }

        private void lstScript_SelectedIndexChanged(object sender, EventArgs e)
        {
            groupBox1.Enabled = false;
            scriptData data = lstScript.SelectedItem as scriptData;
            if (data != null)
                DataToForm(data);
        }

        public void LoadScript(string fileName)
        {
            scripts load = scripts.LoadFromFile(fileName);
            lstScript.Items.Clear();
            foreach (scriptData s in load.scriptList)
                lstScript.Items.Add(s);
            groupBox1.Enabled = false;
        }

        private void btnIPRange_Click(object sender, EventArgs e)
        {
            CaptureRange cr = new CaptureRange();
            if (cr.ShowDialog() == DialogResult.OK)
            {
                lstScript.Items.Clear();
                foreach (scriptData s in cr.m_result.scriptList)
                    lstScript.Items.Add(s);
                groupBox1.Enabled = false;
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                LoadScript(openFileDialog1.FileName);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                scripts save = new scripts();
                foreach (scriptData s in lstScript.Items)
                    save.scriptList.Add(s);
                save.SaveToFile(saveFileDialog1.FileName);
            }
        }

        private void btnNew2_Click(object sender, EventArgs e)
        {
            lstScript.Items.Clear();
            groupBox1.Enabled = false;
        }

        public void Exit()
        {
            m_bExit = true;
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            if (!m_bRunning)
                Run(false, null);
            else
                m_bExit = true;
        }

        private void btnRunUnique_Click(object sender, EventArgs e)
        {
            if (lstScript.SelectedItem != null)
                Run(true, null);
        }

        private void AppendLog(string format, params object[] objs)
        {
            txtLog.AppendText(string.Format(format, objs));
            txtLog.SelectionStart = txtLog.TextLength;
            txtLog.ScrollToCaret();
        }

        private void AppendLog(string format)
        {
            txtLog.AppendText(format);
            txtLog.SelectionStart = txtLog.TextLength;
            txtLog.ScrollToCaret();
        }

        public void Run(bool bSelection, string destination)
        {
            if (destination==null)
            {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowNewFolderButton = true;
            fbd.Description = "Select destination directory";
            if (fbd.ShowDialog() == DialogResult.OK)
                destination = fbd.SelectedPath;
            }

            if (destination!=null)
            {
                panelList.Enabled = false;
                panelButton.Enabled = false;
                groupBox1.Enabled = false;

                btnRun.Text = "Cancel";
                m_bExit = false;
                m_bRunning = true;

                int start = 0, end = lstScript.Items.Count;
                if (bSelection)
                {
                    start = lstScript.SelectedIndex;
                    end = start + 1;
                }

                for (int i = start; i < end && m_bExit==false; i++)
                {
                    lstScript.SelectedIndex = i;
                    scriptData sd = lstScript.Items[i] as scriptData;

                    navigator1.Size = sd.initialSize;
                    AppendLog("Start navigation to {0}\r\n", sd.url);
                    navigator1.Navigate(sd.url);
                    AppendLog("Wait for page to complete {0}s\r\n", sd.timeOut);
                    m_timeout = sd.timeOut;
                    m_completeTime = DateTime.Now.AddSeconds(m_timeout);
                    while (DateTime.Now < m_completeTime && m_bExit==false)
                    {
                        System.Threading.Thread.Sleep(10);
                        Application.DoEvents();
                    }

                    if (!m_bExit)
                    {
                        AppendLog("Navigation completed, wait {0}ms\r\n", sd.waitBeforeCapture);
                        navigator1.AutoResize(sd.bAutoResize, sd.sizeOffset.Width, sd.sizeOffset.Height);
                        navigator1.ScrollBarsEnabled(!sd.bRemoveScrollBar);
                        DateTime time = DateTime.Now.AddMilliseconds(Math.Min(1000, sd.waitBeforeCapture));
                        while (DateTime.Now < time && m_bExit==false)
                        {
                            System.Threading.Thread.Sleep(10);
                            Application.DoEvents();
                        }
                    }

                    if (!m_bExit)
                    {
                        AppendLog("Stop navigation and capture page\r\n");
                        navigator1.Stop();

                        Bitmap bmp = navigator1.CaptureBitmap();

                        Bitmap finalBmp;
                        if (sd.capture != captureMode.Full || sd.resize != resizeMode.No)
                        {
                            Rectangle srcRect;
                            if (sd.capture == captureMode.Full)
                                srcRect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                            else
                                srcRect = sd.captureParam;
                            if (sd.resize == resizeMode.Fixed)
                                finalBmp = new Bitmap(sd.resizeParam.Width, sd.resizeParam.Height);
                            else if (sd.resize == resizeMode.Percent)
                                finalBmp = new Bitmap(Convert.ToInt32(srcRect.Width * sd.resizeParam.Width / 100),
                                    Convert.ToInt32(srcRect.Height * sd.resizeParam.Height / 100));
                            else // if (sd.resize == resizeMode.No)
                                finalBmp = new Bitmap(srcRect.Width, srcRect.Height);
                            Graphics gr = Graphics.FromImage(finalBmp);
                            Rectangle destRect = new Rectangle(0, 0, finalBmp.Width, finalBmp.Height);
                            gr.DrawImage(bmp, destRect, srcRect, GraphicsUnit.Pixel);
                            gr.Dispose();
                        }
                        else
                            finalBmp = bmp;
                        
                        settings.LicenceChecking(finalBmp);

                        System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Jpeg;
                        string ext = ".jpg";
                        switch (sd.format)
                        {
                            case formatMode.Bmp:
                                format = System.Drawing.Imaging.ImageFormat.Bmp;
                                ext = ".bmp";
                                break;
                            case formatMode.Png:
                                format = System.Drawing.Imaging.ImageFormat.Png;
                                ext = ".png";
                                break;
                        }
                        string finalFileName = destination + "\\" + sd.name + ext;
                        finalBmp.Save(finalFileName, format);

                        AppendLog("File {0} saved.\r\n", finalFileName);

                        if (finalBmp != bmp)
                            finalBmp.Dispose();
                        bmp.Dispose();
                    }
                }

                if (!m_bExit)
                    AppendLog("Done.\r\n");
                btnRun.Text = "Run";
                panelList.Enabled = true;
                panelButton.Enabled = true;
                m_bRunning = false;
            }
        }

        void navigator1_NavigationCompleteEvent()
        {
            m_completeTime = DateTime.Now.AddSeconds(m_timeout);
        }

        
    }
}
